import { Component, OnInit } from '@angular/core';
import { HttpParams, HttpClient } from '@angular/common/http';
import { LocalStorage } from '@core/local.storage';
import { DatePipe } from '@angular/common';
import { environment } from '../../../../environments/environment';
import { ExportFileService } from '@core/exportFile';
declare const echarts: any;

@Component({
  selector: 'app-detectionproblems',
  templateUrl: './detectionProblems.component.html',
  styles: [`
    .wrap{background:#fff;position:relative;}
    .time{position:absolute;right:10px;top:4px;z-index:9;}
    .m12{margin:0 0 12px 12px;}
    .echartswrap{width:calc(100% - 11px);margin-left:10px;border-left:1px solid #ddd;}
    :host ::ng-deep .problemTable .ant-table-small > .ant-table-content .ant-table-body > table .ant-table-tbody > tr > td{background:#f5fafd;line-height:24px;}
  `]
})

export class DetectionProblemsComponent implements OnInit {
  tabsIndex = 0;
  startValue: any;
  endValue: any;
  dataTable1: any = [];
  dataTable2: any = [];
  dataTable3: any = [];
  dataTable4: any = [];
  popTable: any = [];
  problemsVisible = false;
  repost: any = { 'dataTable1': true, 'dataTable2': true, 'dataTable3': true, 'dataTable4': true, };
  tableScrollFullHeight = { 'overflow-y': 'auto', 'height': document.body.clientHeight - 180 + 'px' };
  lockHeadScroll = { x: '2200px', y: '600px' };

  constructor(
    public ls: LocalStorage,
    private datePipe: DatePipe,
    private exportFile: ExportFileService,
    private http: HttpClient
  ) { }

  ngOnInit() {
    this.endValue = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
    this.startValue = this.datePipe.transform(new Date(), 'yyyy-MM') + '-01';
    // 默认显示第一个tabs
    this.groupbyLvl(this.startValue, this.endValue);
  }

  getTypeData(data) {
    let row = null;
    if (data.length) {
      row = data[data.length - 1];
      const typeData = [];
      const type = ['信号机', '其它', '电子设备', '电源', '电缆绝缘', '轨道电路', '道岔', '监测功能'];
      type.forEach(name => {
        typeData.push({
          name,
          value: row[name]
        })
      });
      return typeData;
    }
  }

  getLevleBarData(data) {
    const seriesData = [];
    const axisData = [];
    data.forEach(el => {
      seriesData.push({
        name: el.WORKSHOPNAME,
        type: 'bar',
        data: [el.I级, el.II级, el.III级],
      });
      axisData.push(el.WORKSHOPNAME);
    });
    return [seriesData, axisData];
  }

  getLevlePieData(data) {
    let row = null;
    if (data.length) {
      row = data[data.length - 1];
      const levelData = [];
      const type = ['I级', 'II级', 'III级'];
      type.forEach(name => {
        levelData.push({
          name,
          value: row[name]
        })
      });
      return levelData;
    }
  }

  // 报警问题等级统计
  groupbyLvl(begindate, enddate) {
    this.apiService(environment.project + '/jzjcProblem/groupbyLvl', begindate, enddate, (data) => {
      const dataTable = [];
      Object.assign(dataTable, data);
      this.addSumRow(dataTable, 'WORKSHOPNAME', 'PERCENT', '总计');
      this.dataTable1 = dataTable;
      // 处理饼图数据
      const levelData = this.getLevlePieData(dataTable);
      if (levelData) {
        this.getEcharts('echart1', '问题级别占比图', '问题统计', levelData);
      }
      const dataInfo = this.getLevleBarData(data);
      if (dataInfo && dataInfo[0].length) {
        this.getEcharts_bar('echart_level', dataInfo[1], ['I级', 'II级', 'III级'], dataInfo[0]);
      }
    });
    this.repost.dataTable1 = false;
  }
  // 报警类型统计
  groupbyType(begindate, enddate) {
    this.apiService(environment.project + '/jzjcProblem/groupbyType', begindate, enddate, (data) => {
      const table1 = [];
      Object.assign(table1, data);
      const table2 = [];
      // 未整改&已销号
      this.apiService(environment.project + '/jzjcProblem/groupByType1', begindate, enddate, (res) => {
        const resdata = [];
        Object.assign(resdata, res);
        if (resdata.length) {
          const array = [];
          for (const item of table1) {
            array.push(item);
          }
          this.addSumRow(array, 'WORKSHOPNAME', 'PERCENT', '总计');
          this.addSumRow(array, 'WORKSHOPNAME', 'PERCENT', '占比');

          this.dataTable2 = array;
          for (let i = 0; i < array.length - 1; i++) {
            table2.push(array[i]);
          }
          // 追加数据
          if (resdata[0]) {
            resdata[0].C = resdata[0].TOTAL;
            resdata[0].WORKSHOPNAME = '未销号';
            array.splice(array.length - 2, 0, resdata[0]);
          }
          if (resdata[1]) {
            resdata[1].C = resdata[1].TOTAL;
            resdata[1].WORKSHOPNAME = '已销号';
            array.splice(array.length - 2, 0, resdata[1]);
          }
          // 处理饼图数据
          const typeData = this.getTypeData(table2);
          if (typeData) {
            this.getEcharts('echart2', '问题类型占比图', '问题统计', typeData);
          }
        }
      });

    });
    this.repost.dataTable2 = false;
  }
  // 报警线别统计
  groupbyLine(begindate, enddate) {
    this.apiService(environment.project + '/jzjcProblem/groupbyLine', begindate, enddate, (data) => {
      const dataTable = [];
      Object.assign(dataTable, data);
      this.addSumRow(dataTable, 'NAME', 'PERCENT', '总计');
      this.dataTable3 = dataTable;
      // 处理饼图数据
      if (dataTable.length) {
        this.getEcharts('echart3', '问题线别占比图', '问题统计', this.seriesData('name', data));
      }
    });
    this.repost.dataTable3 = false;
  }
  // 报警车间统计
  groupbyCJ(begindate, enddate) {
    this.apiService(environment.project + '/jzjcProblem/groupbyType', begindate, enddate, (data) => {
      const dataTable = [];
      Object.assign(dataTable, data);
      this.addSumRow(dataTable, 'WORKSHOPNAME', 'PERCENT', '总计');
      this.dataTable4 = dataTable;
      // 处理饼图数据
      const typeData = this.getTypeData(dataTable);
      if (typeData) {
        this.getEcharts('echart_cj', '车间占比图', '问题统计', this.seriesData('', data));
      }
    });
    this.repost.dataTable4 = false;
  }

  /**
   * 给data加上合计行
   * name 总计字段的名称
   * percent 占比字段的名称
   */
  addSumRow(data, name, percent, rowName) {
    let keys = [];
    const sum: any = {};
    if (!data.length) {
      return;
    }
    data.forEach(row => {
      if (!keys.length) {
        keys = Object.keys(row);
      }
      keys.forEach(key => {
        if (!isNaN(+row[key])) {
          if (sum[key]) {
            sum[key] += +row[key]
          } else {
            sum[key] = +row[key]
          }
          sum[name] = rowName;
          sum[percent] = "100";
        }
      });
    });
    data.push(sum);
    if (rowName === '占比') {
      const allNumber = data[data.length - 2];
      const thisRow = data[data.length - 1];
      for (const item of Object.keys(thisRow)) {
        switch (item) {
          case 'WORKSHOPNAME':
            thisRow[item] = rowName;
            break;
          case 'C':
            thisRow[item] = '100%';
            break;
          default:
            thisRow[item] = (allNumber[item] / allNumber.C * 100).toFixed(2) + '%';
            break;
        }
      }
    }
    return data;
  }
  // 详情弹出层
  detail(row, nodetype, tableType) {
    this.problemsVisible = true;
    let url = '';
    switch (row.WORKSHOPNAME) {
      case "未销号":
        url = environment.project + '/jzjcProblem/groupDetail?orgid=' + tableType + '&nodetype=' + nodetype + '&cancled=0';
        break;
      case "已销号":
        url = environment.project + '/jzjcProblem/groupDetail?orgid=' + tableType + '&nodetype=' + nodetype + '&cancled=1';
        break;
      case "总计":
        url = environment.project + '/jzjcProblem/groupDetail?orgid=' + tableType + '&nodetype=' + nodetype;
        break;
      case "占比":
        url = environment.project + '/jzjcProblem/groupDetail?orgid=' + tableType + '&nodetype=' + nodetype;
        break;
      default:
        switch (tableType) {
          case 'LINE':
            url = environment.project + '/jzjcProblem/groupDetail?orgid=' + row.ID + '&nodetype=' + nodetype;
            break;
          default:
            url = environment.project + '/jzjcProblem/groupDetail?orgid=' + row.WORKSHOPID + '&nodetype=' + nodetype;
            break;
        }
        break;
    }
    if (this.startValue) {
      url += '&begindate=' + this.datePipe.transform(this.startValue, 'yyyy-MM-dd');
    }
    if (this.endValue) {
      url += '&enddate=' + this.datePipe.transform(this.endValue, 'yyyy-MM-dd');
    }
    this.popTable = [];
    this.http.get(url).subscribe((res: any) => {
      if (res.msg === "Ok") {
        if (res.data.length) {
          this.popTable = res.data[0];
          for (const item of this.popTable) {
            switch (item.status) {
              case '0': item.new_status = '未处理'; break;
              case '1': item.new_status = '已下发'; break;
              case '2': item.new_status = '已签收'; break;
              case '3': item.new_status = '上报调度'; break;
              case '4': item.new_status = '申请延期'; break;
              case '5': item.new_status = '延期同意'; break;
              case '6': item.new_status = '延期驳回'; break;
              case '7': item.new_status = '申请销号'; break;
              case '8': item.new_status = '销号同意'; break;
              case '9': item.new_status = '销号驳回'; break;
              case '10': item.new_status = '逾期销号'; break;
            }
            switch (item.problemlevel) {
              case '1': item.new_problemlevel = 'I 级'; break;
              case '2': item.new_problemlevel = 'II 级'; break;
              case '3': item.new_problemlevel = 'III 级'; break;
            }
            switch (item.cancle) {
              case '0': item.new_cancle = '否'; break;
              case '1': item.new_cancle = '提交'; break;
              case '2': item.new_cancle = '是'; break;
              case '3': item.new_cancle = '逾期未整改'; break;
            }
          }
        }
      }
    });
  }
  problemsOk() {
    this.problemsVisible = false;
  }
  // 导出
  download() {
    let exporttype = '';
    let filename = '';
    switch (this.tabsIndex) {
      case 0:
        exporttype = '1';
        filename = '集中监测分析问题按问题级别统计';
        break;
      case 1:
        exporttype = '2';
        filename = '集中监测分析问题按问题类型统计';
        break;
      case 2:
        exporttype = '3';
        filename = '集中监测分析问题按线别统计';
        break;
      case 3:
        exporttype = '2';
        filename = '集中监测分析问题按车间统计';
        break;
    }
    let begin = '';
    let end = '';
    if (this.startValue) {
      begin = this.datePipe.transform(this.startValue, 'yyyy-MM-dd')
    }
    if (this.endValue) {
      end = this.datePipe.transform(this.endValue, 'yyyy-MM-dd')
    }
    const params = new HttpParams()
      .set('exporttype', exporttype)
      .set('begindate', begin)
      .set('enddate', end);
    this.exportFile.postDown(environment.project + '/jzjcProblem/groupExport', params, filename + '.xls');
  }
  apiService(link, begindate, enddate, callback) {
    if (begindate) {
      link += '&begindate=' + this.datePipe.transform(begindate, 'yyyy-MM-dd');
    }
    if (enddate) {
      link += '&enddate=' + this.datePipe.transform(enddate, 'yyyy-MM-dd');
    }
    if (link) {
      link = link.replace('&', '?');
    }
    this.http.get(link).subscribe((res: any) => {
      if (!res.code) {
        if (res.data.length) {
          callback(res.data[0]);
        } else {
          callback([]);
        }
      }
    });
  }
  seriesData(name, data) {
    const seriesData: any = [];
    for (const item of data) {
      seriesData.push({
        'name': name == 'name' ? item.NAME : item.WORKSHOPNAME,
        'value': item.C
      });
    }
    return seriesData;
  }
  search() {
    this.repost.dataTable1 = true;
    this.repost.dataTable2 = true;
    this.repost.dataTable3 = true;
    this.viewCont(this.tabsIndex);
  }
  tabsChange(e) {
    this.viewCont(e);
  }
  viewCont(e) {
    switch (e) {
      case 0:
        this.groupbyLvl(this.startValue, this.endValue);
        break;
      case 1:
        this.groupbyType(this.startValue, this.endValue);
        break;
      case 2:
        this.groupbyLine(this.startValue, this.endValue);
        break;
      case 3:
        this.groupbyCJ(this.startValue, this.endValue);
        break;
    }
  }
  getEcharts(id, title, seriesName, seriesData) {
    const opt = {
      title: {
        text: title,
        x: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
      },
      series: [
        {
          name: seriesName,
          type: 'pie',
          radius: '50%',
          center: ['50%', '50%'],
          label: {
            normal: {
              formatter: '{b} {c} \n({d}%)'
            }
          },
          data: seriesData,
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    };
    const dom = document.getElementById(id);
    if (dom) {
      const ecObj = echarts.getInstanceByDom(dom);
      if (ecObj) {
        ecObj.setOption(opt, true);
      } else {
        echarts.init(dom).setOption(opt, true);
      }
    }
  }

  getMaxValue(seriesData) {
    const maxValues = [0, 0, 0];
    seriesData.forEach(series => {
      for (let index = 0; index < 3; index++) {
        if (series.data[index] > maxValues[index]) {
          maxValues[index] = series.data[index];
        }
      }
    });
    const sort = maxValues.sort((a, b) => b - a);
    return sort[0];
  }

  getEcharts_bar(id, legends, xAxisData, seriesData) {
    const labelOption = {
      show: true,
      position: 'insideBottom',
      // distance: app.config.distance,
      // align: app.config.align,
      // verticalAlign: app.config.verticalAlign,
      // rotate: 90,
      // formatter: '{c}  {a}',

      fontSize: 16,
      // rich: {
      //   name: {
      //     textBorderColor: '#fff'
      //   }
      // }
    };
    const _fomator = (params) => {
      const sn = params.seriesName;
      const v = params.value;
      const _sn = Array.from(sn);
      _sn.push(`\n(${v})`);
      return _sn.join('\n');
    };
    if (seriesData.length) {
      const maxValue = this.getMaxValue(seriesData);
      seriesData.forEach(series => {
        const _lp: any = {};
        Object.assign(_lp, labelOption);
        _lp.formatter = _fomator;
        series.label = { normal: _lp };
        // for (let index = 0; index < 3; index++) {
        //   if (series.data[index] < (maxValue / 2)) {
        //     _lp.position = 'top';
        //   }
        // }
      });
    }
    const opt = {
      type: 'bar',
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      barGap: '0',
      legend: {
        data: legends
        // data: ['Forest', 'Steppe', 'Desert', 'Wetland']
      },
      xAxis: [
        {
          type: 'category',
          axisTick: { show: false },
          data: xAxisData
        }
      ],
      yAxis: [
        {
          type: 'value'
        }
      ],
      series: seriesData
      // series: [
      //   {
      //     name: 'Forest',
      //     type: 'bar',
      //     barGap: 0,
      //     label: {
      //       normal: {
      //         show: true,
      //         position: 'inside'
      //       }
      //     },
      //     data: [320, 332, 301]
      //   },
      // ]
    };
    const dom = document.getElementById(id);
    if (dom) {
      const ecObj = echarts.getInstanceByDom(dom);
      if (ecObj) {
        ecObj.setOption(opt, true);
      } else {
        echarts.init(dom).setOption(opt, true);
      }
    }
    // echarts.init(document.getElementById(id)).setOption(opt, true);
  }
}